package com.imay.live.fragment.dynamics;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.imay.base.activity.BaseActivity;
import com.imay.live.Constants;
import com.imay.live.activity.MainActivity2;
import com.imay.live.activity.ProfileActivity;
import com.imay.live.activity.discovery.DynamicActivity;
import com.imay.live.activity.dynamics.LabelFeedsActivity;
import com.imay.live.activity.dynamics.LabelFeedsDetailActivity;
import com.imay.live.heartlikeslib.hearthikesview.HeartLikeView;
import com.imay.live.helper.EventHelper;
import com.imay.live.manager.DynamicsLinearManager2;
import com.imay.live.model.FeedModel;
import com.imay.live.view.refresh.RefreshView;
import com.imay.live.R;
import com.imay.tbas_api.IMYTBASObject;
import com.lcodecore.tkrefreshlayout.footer.LoadingView;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.ArrayList;
import java.util.List;

import static com.imay.live.activity.dynamics.LabelFeedsDetailActivity.POSITION;

/**
 * 线性动态
 * Created by chan on 2017/3/25.
 */
public class LinearFragment extends DynamicsBaseFragment implements OnTouchHeartListener, DynamicsRecall {
    public final static String FOLLOW = "canfollow";
    private DynamicsLinearManager2 manager;

    private HeartLikeView mHeartLikeView;
    private int playerPosition;
    private IMYTBASObject dynamicsupdate;
    private boolean isVisibleHint = true;
    private boolean applayoutHide = false;

    public DynamicsLinearManager2 getManager() {
        return manager;
    }

    public static LinearFragment newInstance() {
        LinearFragment fragment = new LinearFragment();
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_dynameics_linear;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (getParentFragment() instanceof DynamicsFragment) {
            ((DynamicsFragment) getParentFragment()).setLinearRecall(this);
        }
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        isLoading = false;

        FeedModel feedModel = getActivity().getIntent().getParcelableExtra(DynamicActivity.MODEL);
        boolean canfollow = getActivity().getIntent().getBooleanExtra(FOLLOW, false);
        ArrayList<FeedModel> feedModels = getActivity().getIntent().getParcelableArrayListExtra(LabelFeedsDetailActivity.FEEDSDATA);
        final int position = getActivity().getIntent().getIntExtra(POSITION, -1);
        initWidget(feedModel != null || canfollow);
        initListener();
        if (feedModel != null) {
            ArrayList<Object> multiItemEntities = new ArrayList<Object>();
            multiItemEntities.add(feedModel);
            setDatas(multiItemEntities);
            mRefreshLayout.setEnableLoadmore(false);
            mRefreshLayout.setEnableRefresh(true);
        } else if (feedModels != null && !feedModels.isEmpty()) {
            ArrayList<Object> multiItemEntities = new ArrayList<Object>();
            multiItemEntities.addAll(feedModels);
            setDatas(multiItemEntities);
            mRefreshLayout.setEnableLoadmore(false);
            mRefreshLayout.setEnableRefresh(false);
            if (position != -1 && position < feedModels.size()) {
                scrollToPosition(position);
            }
        }
    }

    /**
     * 初始化监听器
     */
    protected void initListener() {
        super.initListener();

        // 监听数据改变进行布局刷新 1、评论；2、点赞；3、发表动态
        dynamicsupdate = new IMYTBASObject(false);
        dynamicsupdate.stringCommand = EventHelper.EVENT_DYNAMICS_UPDATE;
        dynamicsupdate.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(IMYTBASObject imytbasObject) {
                if (!TextUtils.isEmpty(imytbasObject.stringData)) {
                    JSONObject jsonObject = JSON.parseObject(imytbasObject.stringData);
                    int action = jsonObject.getIntValue(Constants.DynamicsUpdate.DYNAMICS_ACTION_KEY);
                    FeedModel feed = JSON.parseObject(imytbasObject.stringData, FeedModel.class);
                    List<Object> objects = manager.getmAdapter().getData();
                    switch (action) {
                        case Constants.DynamicsUpdate.ACTION_DYNAMICS_MODIFY:
                            int position = 0;
                            for (Object object : objects) {
                                if (object instanceof FeedModel) {
                                    FeedModel item = (FeedModel) object;
                                    if (item.getFeedId() == feed.getFeedId()) {
                                        break;
                                    }
                                }
                                position++;
                            }
                            if(manager == null){
                                break;
                            }
                            FeedModel feedModel = (FeedModel) manager.getmAdapter().getItem(position);
                            feedModel.setMsg(feed.getMsg());
                            feedModel.setCountLike(feed.getCountLike());
                            feedModel.setIsLike(feed.isIsLike());
                            feedModel.setCountComment(feed.getCountComment());
                            feedModel.setAtUsers(feed.getAtUsers());
                            feedModel.setLabels(feed.getLabels());
                            manager.getmAdapter().notifyItemChanged(position);
//                            manager.stop();
//                            manager.getmAdapter().notifyItemChanged(position);
                            break;
                    }
                }
            }
        });
        dynamicsupdate.addEventListenWithTBASObject();
    }


    /**
     * 加载控件
     */
    private void initWidget(boolean visiableFeed) {
        mHeartLikeView = $(R.id.hlv_dynamics_content);
        mRecyclerView = $(R.id.rcv_dynamics_content);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getContext())
                .colorResId(R.color.bg_f8)
                .sizeResId(R.dimen.size_5dp)
                .marginResId(R.dimen.dp_10, R.dimen.dp_10)
                .build());
        manager = new DynamicsLinearManager2(this.getFragmentManager(), getActivity(), mRecyclerView, getContentView(), this, visiableFeed, 0);

        mRefreshLayout = $(R.id.dynamics_trl_refresh);
        RefreshView headerView = new RefreshView(getActivity());
        mRefreshLayout.setHeaderView(headerView);
        mRefreshLayout.setBottomView(new LoadingView(getActivity()));
        mRefreshLayout.setEnableLoadmore(true);
        mRefreshLayout.setEnableOverScroll(false);

        mRefreshLayout.addView(loadView, 0, new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        loadView.startLoading();
    }

    /**
     * 加载数据
     *
     * @param list
     */
    @Override
    public void setDatas(List list) {
        if (mRecyclerView.getVisibility() == View.INVISIBLE) {
            mRecyclerView.setVisibility(View.VISIBLE);
        }
        loadView.stopLoading();
        if (list.isEmpty()) {
            loadView.loadError();
        }
        isLoading = false;
        if(manager != null){
            manager.setNewData(list);
            mRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    if (isVisibleHint) {
                        manager.play(0);
                    }
                }
            });
        }
    }

    /**
     * 加载数据
     *
     * @param list
     */
    @Override
    public void addDatas(List list) {
        if (mRecyclerView.getVisibility() == View.INVISIBLE) {
            mRecyclerView.setVisibility(View.VISIBLE);
        }
        if(manager != null){
            manager.addDatas(list);
        }
        isLoading = false;
    }

    /**
     * 加载数据
     *
     * @param list
     */
    @Override
    public void replaceDatas(int position, List list) {
        if(manager != null){
            manager.addDatas(position, list);
        }
        isLoading = false;
    }

    /**
     * 替换评论数
     *
     * @param position
     * @param countComment
     */
    public void replaceData(int position, int countComment) {
        FeedModel feedModel = (FeedModel) manager.getmAdapter().getItem(position);
        feedModel.setCountComment(countComment);
        if(manager != null){
            manager.getmAdapter().notifyItemChanged(position);
        }
    }


    /**
     * 弹心
     *
     * @param x
     * @param y
     * @param feedId
     * @param status true赞，false取消赞
     */
    @Override
    public void showHeart(float x, float y, int feedId, boolean status) {
        if (status) {
            float dy;
            if (applayoutHide) {
                dy = y;
            } else {
                dy = y - ((BaseActivity) getActivity()).getTitleBar().getMeasuredHeight();
            }
            mHeartLikeView.showHeartView(x, dy);
            likeCreate(feedId);// 点赞
        } else {
            likeDel(feedId);// 取消赞
        }
    }

    /**
     * 关闭声音
     *
     * @param position
     */
    @Override
    public void onVoiceClick(int position) {
        if(manager != null){
            manager.setVoice(position);
        }
    }

    @Override
    public void jinClick(String label) {
        LabelFeedsActivity.startActivity(getActivity(), label);
    }

    @Override
    public void atClick(String nick, long uid) {
        ProfileActivity.start(getActivity(), uid);
    }

    @Override
    public void suggestTouch(boolean status) {
        if (status) {
            if (getActivity() instanceof MainActivity2) {
                ((MainActivity2) getActivity()).closeCoordBehavior();
            }
        } else {
            if (getActivity() instanceof MainActivity2) {
                ((MainActivity2) getActivity()).openCoordBehavior();
            }
        }
    }

    /**
     * 设置是否到尾部
     *
     * @param end
     */
    public void setEnd(boolean end) {
        isEnd = end;
        if (end) {

        } else {

        }
    }

    /**
     * 滚动到对应位置
     *
     * @param position
     */
    @Override
    public void scrollToPosition(final int position) {
        LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
        linearLayoutManager.scrollToPositionWithOffset(position, 0);
        mRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                if (isVisibleHint) {
                    if(manager != null){
                        manager.play(position);
                    }
                }
            }
        });
    }

    @Override
    public void scrolltoTop() {
        super.scrolltoTop();
    }

    @Override
    public void netError() {
        mRecyclerView.setVisibility(View.INVISIBLE);
        loadView.netError();
    }

    /**
     * ======父fragment操作子fragment=========
     */
    @Override
    public void play() {
        isVisibleHint = true;
        if (manager != null) {
            if (playerPosition != -1) {
                manager.play(playerPosition);
            } else {
                manager.play(0);
            }
        }
    }

    @Override
    public void stop() {
        isVisibleHint = false;
        if (manager != null) {
            final int position = manager.stop();
            playerPosition = position != -1 ? position : playerPosition;
        }
    }

    protected void refresh() {
        if (manager != null) {
            manager.notifyItemMoved();
        }
    }

    /**
     * 完成刷新
     */
    @Override
    public void setRefreshFinish() {
        if (mRefreshLayout != null) {
            mIsRefreshing = false;
            mRefreshLayout.finishRefreshing();
        }
    }

    /**
     * 完成加载
     */
    @Override
    public void setLoadFinish() {
        if (mRefreshLayout != null) {
            mIsRefreshing = false;
            mRefreshLayout.finishLoadmore();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        stop();
    }

    @Override
    public void onResume() {
        super.onResume();
        play();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (manager != null) {
            manager.release();
        }
        if (dynamicsupdate != null) {
            dynamicsupdate.destroy();
        }
    }

    @Override
    public void loadError(String string) {
        super.loadError(string);
    }

    @Override
    public RecyclerView getRecyclerView() {
        return mRecyclerView;
    }

    @Override
    public void appLayoutStatus(boolean applayoutHide) {
        this.applayoutHide = applayoutHide;
    }
}
